const express = require('express')
var bodyParser = require('body-parser')

const app = express()
const port = 3000

app.use(express.static('www'))
//解析body中间件
app.use(bodyParser.json({limit:'100mb'}));

app.use('/uploads',express.static('uploads'))

app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type,token');
    next();
  });
// app.use(require('cors')())

//wx
const wxRouter = require('./wx')
wxRouter(app)

//admin
const adminRouter = require('./admin')
adminRouter(app)


//token缓存
let tokens = {

}


//登录拦截中间件
function loginRouter(req,res,next){
    let token = req.headers.token
    if(token){
        SQLHelper(`select * from session where id = ${token}`).then(ret =>{
            if(ret.length){
                let session = ret[0]
                req.session = {
                    userId:session.userId,
                    userName:session.userName
                }
                next()
            }else{
                res.status(406).send({errorMsg:'当前用户未登录'})
            }
         })
    }else{
        res.status(405).send({errorMsg:'缺少token,请先进行登录'})
    }
}
//让初登录以外的所有小程序接口都先验证登录
app.use('/wx',loginRouter)

const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
  
return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : `0${n}`
}

///微信登陆
app.get('/wxlogin',(req, res,next) => {
    //console.log(req.header)
    //console.log(req)
    let code = req.query.code
    let appid = 'wx0516a43734dc3ab8'
    let secret = 'aec7d86d6ffd480c759233749ef4f841'
    https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) =>{
        ret.on('data', (ret) =>{
             ret = JSON.parse(ret.toString())
             var openid = ret.openid
            //res.send(ret.toString())
            if(!openid){
                res.send({errorMsg: ret.error || '获取openid错误'})
            }else{
                let queryMember = `select * from member where openId = '${openid}'`
                SQLHelper(queryMember).then(membersRet =>{
                    if(membersRet.length){//用户已存在
                        req.member = membersRet[0]
                        next()
                    }else{//用户不存在
                        SQLHelper(`INSERT INTO member (openId) VALUES ('${openid}')`).then(newMember =>{
                           SQLHelper(queryMember).then(newMember =>{
                            req.member = membersRet[0]
                            next()
                           })
                        })
                    }
                })
            }
        });

    }).on('error', (e) =>{
        console.error(e);
        res.send({errorMsg:'获取openid错误'});
        }
    );
},(req,res) => {
    let member = req.member
    let token = snowflake()
    //缓存tokens到session表
    SQLHelper(`
    INSERT INTO session(id,userId,userName,inTime,platform)
    VALUES(${token},'${member._id}','${member.nickName}','${formatTime(new Date())}','wx')
    `).then(ret =>{
        res.send({
            nickName:member.nickName,
            token,
            openId:member.openId,
            avatarUrl:member.avatarUrl,
            _id:member._id
        })
    })
})
//修改用户信息
app.put('/wx/member',(req,res) =>{
     let userInfo = req.body
     console.log(userInfo,req.query)
     SQLHelper(`
     update member 
     set nickName = '${userInfo.nickName}',avatarUrl = '${userInfo.avatarUrl}'
     where _id = ${req.session.userId}
     `).then(ret =>{
         console.log(ret)
         res.send({})
     })
})


///获取收货地址列表
app.get('/wx/address',loginRouter,(req,res) =>{
    if(req.session.userId){
        SQLHelper(`
        select * from address where state = 1 and memberId = ${req.session.userId}
        `).then(ret =>{
            res.send(ret)
        })
    }else{
        res.send({errorMsg:'请输入memberId'})
    }
})

///获取收货地址详情
app.get('/wx/address/detail',loginRouter,(req,res) =>{
    if(req.query.addressId){
        SQLHelper(`
        select * from address where _id = ${req.query.addressId}
        `).then(ret =>{
            res.send(ret.length ? ret[0] : {errorMsg:'未获取到地址详情'})
        })
    }else{
        res.send({errorMsg:'请输入addressId'})
    }
})

///新增收货地址
app.post('/wx/address',(req,res) =>{
    if(req.body.receiver && req.body.phone && req.body.city){
        SQLHelper(`
        INSERT INTO address (state,memberId,receiver,phone,city,area)
        VALUES(1,'${req.session.userId}','${req.body.receiver}','${req.body.phone}','${req.body.city}','${req.body.area || ''}')
        `).then(ret =>{
            res.send(ret)
        })
    }else{
        res.send({errorMsg:'传入参数错误'})
    }
})

///修改收货地址
app.put('/wx/address',(req,res) =>{
    if(req.body.addressId){
        let updateKey = ['receiver','phone','city','area']
        let updateValues = []
        for(let i = 0; i < updateKey.length; i ++){
            let key = updateKey[i],value = req.body[key]
            if(value) updateValues.push(`${key}='${value}'`)
        }
        SQLHelper(`UPDATE address set ${updateValues.join(',')} WHERE _id = ${req.body.addressId}`).then(ret =>{
            res.send(ret)
        })
    }else{
        res.send({errorMsg:'传入参数错误'})
    }
})
///修改为默认地址
app.put('/wx/address/default',(req,res) =>{
    let addressId = req.body.addressId,memberId = req.session.userId,isDefault = req.body.isDefault == 1 ? 1 : 0
    if(addressId && memberId){
        if(isDefault == 1){//设置为默认地址
            SQLHelper(`
            UPDATE address
            set isDefault = 0
            WHERE  isDefault = 1 AND memberId = ${memberId}
            `).then(ret =>{
                SQLHelper(`
                UPDATE address
                set isDefault = 1
                WHERE _id = ${addressId}
                `).then(ret =>{
                res.send(ret)
            })
          })
        }else{//取消默认地址
            SQLHelper(`
                UPDATE address
                set isDefault = 0
                WHERE _id = ${addressId}
                `).then(ret =>{
                res.send(ret)
            })
        }
    }else{
        res.send({errorMsg:'传入参数错误'})
    }
})


//删除地址
app.delete('/wx/address',(req,res) =>{
    let addressId = req.body.addressId
    if(addressId){
        SQLHelper(`
        UPDATE address
        set state = 0
        WHERE _id = ${addressId}
        `).then(ret =>{
            res.send(ret)
      })
    }else{
        res.send({errorMsg:'传入参数错误'})
    }
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})
